package com.chinapost.service.impl;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.excelUtil.ExcelUtil;
import com.chinapost.po.Tdept;
import com.chinapost.po.Twdry;
import com.chinapost.po.Twdxx;
import com.chinapost.service.WdryServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Wdry;

@Service("wdryService")
public class WdryServiceImpl implements WdryServiceI {

	@Autowired
	private BaseDaoI<Twdry> wdryDao;
	@Autowired
	private BaseDaoI<Tdept> deptDao;
	@Autowired
	private BaseDaoI<Twdxx> wdxxDao;

	@Override
	public DataGrid datagrid(Wdry wdry) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(wdry)));
		dg.setTotal(total(wdry));
		return dg;
	}

	private Long total(Wdry wdry) {
		String hql = "select count(*) from Twdry t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(wdry, hql, params);
		return wdryDao.count(hql, params);
	}

	private List<Twdry> find(Wdry wdry) {
		String hql = "from Twdry t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(wdry, hql, params);
		if (wdry.getOrder() != null && wdry.getSort() != null) {
			hql += " order by " + wdry.getSort() + " " + wdry.getOrder();
		}
		return wdryDao.find(hql, params, wdry.getPage(), wdry.getRows());
	}

	private List<Wdry> listRows(List<Twdry> lt) {
		List<Wdry> rows = new ArrayList<Wdry>();
		if (lt != null && lt.size() > 0) {
			for (Twdry t : lt) {
				Wdry sub = new Wdry();
				BeanUtils.copyProperties(t, sub);
				sub.setDeptId(t.getTdept().getCid());
				sub.setDeptName(t.getTdept().getCname());
				sub.setWdid(t.getTwdxx().getCid());
				sub.setWdName(t.getTwdxx().getCname());
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Wdry wdry, String hql, Map<String, Object> params) {
		if (wdry != null && wdry.getCid() != null && !wdry.getCid().trim().equals("")) {
			hql += " and t.cid = :id ";
			params.put("id", wdry.getCid());
		}
		if (wdry != null && wdry.getCname() != null && !wdry.getCname().trim().equals("")) {
			hql += " and t.cname like :wdryname ";
			params.put("wdryname", "%%" + wdry.getCname() + "%%");
		}
		if (wdry != null && !StringUtils.isEmpty(wdry.getWdid())) {
			hql += " and t.twdxx.cid = :wdid";
			params.put("wdid", wdry.getWdid());
		}
		if (wdry != null && wdry.getDeptIds() != null && wdry.getDeptIds().size() > 0) {
			hql += " and t.tdept.cid in(:deptids)";
			params.put("deptids", wdry.getDeptIds());
		}
		return hql;
	}

	@Override
	public List<Wdry> listWdry() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void add(Wdry wdry) {
		Twdry twdry = new Twdry();
		Date d = new Date();
		BeanUtils.copyProperties(wdry, twdry);
		twdry.setCcreatedate(new Timestamp(d.getTime()));
		twdry.setCmodifydate(new Timestamp(d.getTime()));
		twdry.setTdept(deptDao.get(Tdept.class, wdry.getDeptId()));
		twdry.setTwdxx(wdxxDao.get(Twdxx.class, wdry.getWdid()));
		wdryDao.save(twdry);
	}

	@Override
	public void edit(Wdry wdry) {
		Twdry t = wdryDao.get(Twdry.class, wdry.getCid());
		BeanUtils.copyProperties(wdry, t, new String[] { "ccreatedate", "cbh" });
		Date d = new Date();
		t.setCmodifydate(new Timestamp(d.getTime()));
		t.setTdept(deptDao.get(Tdept.class, wdry.getDeptId()));
		t.setTwdxx(wdxxDao.get(Twdxx.class, wdry.getWdid()));
	}

	@Override
	public void delete(Wdry wdry) {
		String cids = "";
		if (wdry.getIds() != null) {
			String ids = wdry.getIds();
			for (String cid : ids.split(",")) {
				cids += "'" + cid + "'" + ",";
			}
			cids = cids.substring(0, cids.length() - 1);
			String hql = "delete Twdry t where t.cbh in (" + cids + ")";
			wdryDao.executeHql(hql);
		}

	}

	@Override
	public Wdry getWdryById(String id) {
		Twdry t = wdryDao.get(Twdry.class, id);
		Wdry w = new Wdry();
		if (t != null) {
			BeanUtils.copyProperties(t, w);
			if (t.getTdept() != null) {
				w.setDeptId(t.getTdept().getCid());
				w.setDeptName(t.getTdept().getCname());
				w.setWdid(t.getTwdxx().getCid());
				w.setWdName(t.getTwdxx().getCname());
			}
		}
		return w;
	}

	@Override
	public int addWdrys(Wdry wdry) {
		int i = 0;
		String[] fields = { "wdname", "cname", "cbh", "csex", "cyglb" };
		if (wdry != null && !wdry.getFilename().isEmpty()) {
			ExcelUtil eu = new ExcelUtil();
			List<ArrayList<String>> wdryList = eu.read(wdry.getFilename());
			Tdept tdept = deptDao.get(Tdept.class, wdry.getDeptId());
			if (tdept != null) {
				for (ArrayList<String> row : wdryList) {
					String wdname = row.get(0).trim();
					if (!StringUtils.isEmpty(wdname)) {
						String hql = "from Twdxx t where t.cname = :wdname";
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("wdname", wdname);
						Twdxx wd = wdxxDao.get(hql, params);
						if (wd != null) {
							Twdry t = new Twdry();
							t.setTdept(tdept);
							t.setTwdxx(wd);
							Date d = new Date();
							t.setCcreatedate(new Timestamp(d.getTime()));
							t.setCmodifydate(new Timestamp(d.getTime()));
							for (int n = 1; n < row.size(); n++) {
								try {
									org.apache.commons.beanutils.BeanUtils.setProperty(t, fields[n], row.get(n).trim());
								} catch (IllegalAccessException e) {
									e.printStackTrace();
								} catch (InvocationTargetException e) {
									e.printStackTrace();
								}
							}
							wdryDao.save(t);
							i++;
						}
					}
				}
			}
			File f = new File(wdry.getFilename());
			if (f.exists() && f.isFile()) {
				f.delete();
			}
		}
		return i;
	}

}
